package com.lsk.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.lsk.bean.WxBean;
import com.lsk.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 微信营销活动授权拦截器
 * Created by Administrator on 2018/9/14 0014.
 */

public class MobileMarketingAuthorizationInterceptor implements Interceptor {
    Cache cache= Redis.use(PropKit.get("cache.name"));
    @Override
    public void intercept(Invocation ivo) {
        ivo.getController().setUrlPara(System.currentTimeMillis() + "");
        Controller controller = ivo.getController();
        //获取到sessionid
        HttpSession session = controller.getSession();
        Map<String, String[]> map = controller.getParaMap();
        HttpServletRequest request=controller.getRequest();
        StringBuffer beforeurl = request.getRequestURL();
        String tempContextUrl = beforeurl.toString();
        if (tempContextUrl.contains(GlobalParameter.authorizationDomain)==false){//当前域名不是授权域名
            String host="";
            try {
                java.net.URL  javaUrl = new  java.net.URL(beforeurl.toString());
                host = javaUrl.getHost();// 获取主机名
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            String strUrl=beforeurl.toString().replace(host,GlobalParameter.authorizationDomain);
            Syslog.info("重定向域名为    "+strUrl);
            strUrl=getRedirectUrl(strUrl,map);
            ivo.getController().redirect(strUrl);
            return;
        }

        Record temp = new Record().set("parameters", map);
        Object key = session.getAttribute("session_key");
        Object uuidKey = map.get("uuid");
        if (key == null) {//session 为  null
            Object objOrgId=map.get("orgId");
            if (objOrgId!=null ){//orgId 不为空  是正常链接
                Syslog.info("orgId ++++++++++"+map.get("orgId")[0]);
                Object objTimestamp=map.get("timestamp");
                if (objTimestamp==null){//没有时间戳，链接重定向
                    String uuid = UtilUUID.getUUID();
                    cache.setex(uuid, 60 * 60 * 24, temp);
                    String orgId = map.get("orgId")[0];
                    String url = getAuthorizationUrl(orgId, uuid);
                    Syslog.info(" 从定向的参数为 " + url);
                    controller.redirect(url);
                    return;
                }else {
                    String timestamp=map.get("timestamp")[0]; //授权时间 以时间戳为 key 储存信息
                    if (cache.get(timestamp)!=null){//已经授权过
                        ivo.invoke();
                    }else {
                        String uuid = UtilUUID.getUUID();
                        cache.setex(uuid, 60 * 60 * 24, temp);
                        String orgId = map.get("orgId")[0];
                        String url = getAuthorizationUrl(orgId, uuid);
                        Syslog.info(" 从定向的参数为 " + url);
                        controller.redirect(url);
                        return;
                    }
                }

            }else {
                String url="http://www.dingyuankeji.shop/mobileMarketing/index?orgId=30&activityId=29&parentId=";
                controller.redirect(url);
                return;
            }
        } else {
            Object objOrgId=map.get("orgId");
            if (objOrgId!=null ){//uuid 为空  是正常链接
                refreshParameter(key.toString(),map);
                ivo.invoke();
            }else {//不是正常链接，
                String url="http://www.dingyuankeji.shop/mobileMarketing/index?orgId=30&activityId=29&parentId=";
                controller.redirect(url);
                return;
            }
        }
    }

    /*从定向url参数组装*/
    private String getRedirectUrl(String url,Map<String,String[]> parameterMap) {
        url+="?";
        for (Map.Entry<String,String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey().toString();
            url += key+"="+entry.getValue()[0]+"&";
        }
        url=url.substring(0,url.length()-1);
        return url;
    }


    /*刷新参数*/
    public void refreshParameter(String key,Map<String, String[]> map){
        Record temp=cache.get(key);
        Map<String,String[]> tempMap=temp.get("parameters");
        Map<String,String[]> tempMap1=new HashMap<>();
        Iterator<Map.Entry<String,String[]>> entriesTemp = tempMap.entrySet().iterator();
        while (entriesTemp.hasNext()) {
            Map.Entry<String,String[]> entry = entriesTemp.next();
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()[0]);
            String arr[] = {entry.getValue()[0]};
            tempMap1.put(entry.getKey(),arr);
        }
        Iterator<Map.Entry<String,String[]>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String,String[]> entry = entries.next();
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()[0]);
            String arr[] = {entry.getValue()[0]};
            tempMap1.put(entry.getKey(),arr);
        }
        temp.set("parameters",tempMap1);
        cache.setex(key, 60 * 60 * 24, temp);
    }



   /*用户授权*/
    private String getAuthorizationUrl(String orgId,String uuid){
        String appId=operationCache(orgId,uuid);
        String url=SnsAccessTokenApi.getAuthorizeURL(appId,
                "http://"+GlobalParameter.authorizationDomain+"/mobileMarketing/authorizationCallback",
                uuid,false);
        return url;
    }

    public String  operationCache(String orgId,String uuid){
        String sql="SELECT *from weixin_public_account_info where type=0 and orgId="+orgId;
        Record record= Db.findFirstByCache("weixinConfig", MD5.md5(sql),sql);

        String appId="";
        if (record==null){
            WxBean wxBean=new WxBean();
            Syslog.info("获取到的wxBean ："+JsonUtil.getJsonStr(wxBean));
            appId=wxBean.getAppId();
        }else {
            appId=record.getStr("appId");
        }

        Record temp=cache.get(uuid);
        temp.set("appId",appId);
        cache.setex(uuid,60*60*24,temp);
        return appId;
    }




}
